#!/bin/bash

# xiaozhi-server MQTT配置信息获取工具 (Shell版本)
# 用于在不通过管理界面的情况下获取客户端ID、用户名、密码等信息

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}$1${NC}"
}

print_success() {
    echo -e "${GREEN}$1${NC}"
}

print_warning() {
    echo -e "${YELLOW}$1${NC}"
}

print_error() {
    echo -e "${RED}$1${NC}"
}

# 检查依赖
check_dependencies() {
    local missing_deps=()
    
    if ! command -v python3 &> /dev/null; then
        missing_deps+=("python3")
    fi
    
    if ! python3 -c "import yaml" &> /dev/null; then
        missing_deps+=("python3-yaml")
    fi
    
    if [ ${#missing_deps[@]} -ne 0 ]; then
        print_error "❌ 缺少依赖: ${missing_deps[*]}"
        print_info "请安装依赖:"
        print_info "sudo apt update"
        print_info "sudo apt install python3 python3-yaml -y"
        exit 1
    fi
}

# 获取配置值
get_config_value() {
    local key="$1"
    local config_file="$2"
    
    if [ -f "$config_file" ]; then
        python3 -c "
import yaml
import sys
try:
    with open('$config_file', 'r', encoding='utf-8') as f:
        config = yaml.safe_load(f) or {}
    
    keys = '$key'.split('.')
    value = config
    for k in keys:
        if isinstance(value, dict) and k in value:
            value = value[k]
        else:
            value = None
            break
    
    if value is not None and value != 'null':
        print(value)
except:
    pass
"
    fi
}

# 加载配置
load_config() {
    local key="$1"
    
    # 首先尝试从 data/.config.yaml 读取
    local value=$(get_config_value "$key" "main/xiaozhi-server/data/.config.yaml")
    
    # 如果没有找到，尝试从 config.yaml 读取
    if [ -z "$value" ]; then
        value=$(get_config_value "$key" "main/xiaozhi-server/config.yaml")
    fi
    
    echo "$value"
}

# 生成MQTT密码签名
generate_password_signature() {
    local content="$1"
    local secret_key="$2"
    
    python3 -c "
import hmac
import hashlib
import base64
import sys

try:
    content = '$content'
    secret_key = '$secret_key'
    
    hmac_obj = hmac.new(
        secret_key.encode('utf-8'), 
        content.encode('utf-8'), 
        hashlib.sha256
    )
    signature = hmac_obj.digest()
    result = base64.b64encode(signature).decode('utf-8')
    print(result)
except Exception as e:
    sys.stderr.write(f'生成密码签名失败: {e}\n')
    sys.exit(1)
"
}

# 生成用户名
generate_username() {
    python3 -c "
import json
import base64

user_data = {'ip': 'unknown'}
user_data_json = json.dumps(user_data)
username = base64.b64encode(user_data_json.encode('utf-8')).decode('utf-8')
print(username)
"
}

# 主函数
main() {
    print_info "🔍 xiaozhi-server MQTT配置信息获取工具"
    echo "=================================================="
    
    # 检查是否在正确的目录
    if [ ! -d "main/xiaozhi-server" ]; then
        print_error "❌ 请在xiaozhi-esp32-server项目根目录下运行此脚本"
        exit 1
    fi
    
    # 检查依赖
    check_dependencies
    
    # 获取设备ID
    if [ -n "$1" ]; then
        device_id="$1"
    else
        read -p "请输入设备ID (MAC地址，如 11:22:33:44:55:66): " device_id
    fi
    
    if [ -z "$device_id" ]; then
        print_error "❌ 设备ID不能为空"
        exit 1
    fi
    
    # 获取设备型号
    if [ -n "$2" ]; then
        device_model="$2"
    else
        read -p "请输入设备型号 (可选，默认为 default): " device_model
        device_model=${device_model:-"default"}
    fi
    
    echo
    print_info "📱 设备ID: $device_id"
    print_info "📱 设备型号: $device_model"
    echo "--------------------------------------------------"
    
    # 加载配置
    mqtt_gateway=$(load_config "server.mqtt_gateway")
    mqtt_signature_key=$(load_config "server.mqtt_signature_key")
    
    # 检查配置
    if [ -z "$mqtt_gateway" ] || [ "$mqtt_gateway" = "null" ]; then
        print_error "❌ 未配置MQTT网关地址 (server.mqtt_gateway)"
        exit 1
    fi
    
    if [ -z "$mqtt_signature_key" ] || [ "$mqtt_signature_key" = "null" ]; then
        print_error "❌ 未配置MQTT签名密钥 (server.mqtt_signature_key)"
        exit 1
    fi
    
    # 生成配置信息
    group_id="GID_${device_model//[: ]/_}"
    mac_address_safe="${device_id//:/_}"
    mqtt_client_id="${group_id}@@@${mac_address_safe}@@@${mac_address_safe}"
    
    username=$(generate_username)
    password=$(generate_password_signature "${mqtt_client_id}|${username}" "$mqtt_signature_key")
    
    publish_topic="device-server"
    subscribe_topic="devices/p2p/${mac_address_safe}"
    
    # 显示结果
    print_success "✅ MQTT配置信息:"
    echo "📡 MQTT服务器地址: $mqtt_gateway"
    echo "🆔 客户端ID: $mqtt_client_id"
    echo "👤 用户名: $username"
    echo "🔐 密码: $password"
    echo "📤 发布主题: $publish_topic"
    echo "📥 订阅主题: $subscribe_topic"
    
    echo
    echo "=================================================="
    print_info "📋 完整JSON配置:"
    
    # 生成JSON配置
    json_config=$(cat << EOF
{
  "endpoint": "$mqtt_gateway",
  "client_id": "$mqtt_client_id",
  "username": "$username",
  "password": "$password",
  "publish_topic": "$publish_topic",
  "subscribe_topic": "$subscribe_topic"
}
EOF
)
    
    echo "$json_config"
    
    # 保存到文件
    output_file="mqtt_config_${mac_address_safe}.json"
    echo "$json_config" > "$output_file"
    print_success "💾 配置已保存到: $output_file"
    
    echo
    print_warning "💡 提示:"
    echo "1. 这些配置信息可以直接用于MQTT客户端连接"
    echo "2. 客户端ID、用户名、密码都是根据设备ID和配置自动生成的"
    echo "3. 如需修改MQTT网关地址或签名密钥，请编辑 data/.config.yaml 文件"
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [设备ID] [设备型号]"
    echo
    echo "参数:"
    echo "  设备ID    设备的MAC地址，如: 11:22:33:44:55:66"
    echo "  设备型号  设备型号，可选，默认为 default"
    echo
    echo "示例:"
    echo "  $0 11:22:33:44:55:66"
    echo "  $0 11:22:33:44:55:66 esp32"
    echo "  $0  # 交互式输入"
}

# 处理命令行参数
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    show_help
    exit 0
fi

# 运行主函数
main "$@"